package com.tiendung.otalunch;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FriendChecking extends ListActivity 
{
	private static final String PASSPHRASE = "You can never guess me";
	private ArrayList<HashMap<String, String>> friend_list = new ArrayList<HashMap<String, String>>();
	private OtaLunchDatabase db;
	private ProgressDialog dialog;
	public String strId = null;
	public String strRestaurant = null;
	public String strTime = null;
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friends);
		this.db = new OtaLunchDatabase(this);
		
		dialog = ProgressDialog.show(FriendChecking.this, "", "Downloading. Please wait...", true);    	
		queryfriend();	        		 
		dialog.cancel();	        		 
	    
		setListAdapter(new FriendAdapter(this, R.layout.friendrow, friend_list));  
		ListView lv = getListView();  
		
		lv.setTextFilterEnabled(true);  
		lv.setOnItemClickListener(new OnItemClickListener() 
		{    
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// When clicked, show a toast with the TextView text      
				Toast.makeText(getApplicationContext(), "" + position, Toast.LENGTH_SHORT).show();    
			}  
		});
	}
			
	
	private void queryfriend()
    {
    	ArrayList<String> facebook_info = db.select_facebook();
    	final ArrayList<String> friend_id_list = db.select_friends();
    	
    	String friend_ids = null;
    	int i;
    	for (i = 0; i < friend_id_list.size() - 1; i++)
    		friend_ids = friend_ids  + friend_id_list.get(i) + "+";
    	friend_ids = friend_ids  + friend_id_list.get(i);
    	
    	String url;
    	if (facebook_info.size() > 1)
    		url = "http://" + TheTabWidget.serverIP + "/friends.php?id=" + encrypt(facebook_info.get(0)) + "&name=" + encrypt(facebook_info.get(1)) + "&friends=" + friend_ids;
    	else
    		url = "http://" + TheTabWidget.serverIP + "/friends.php?id=NULL&name=NULL&friends=" + friend_ids;
    	
    	try {
    		DefaultHttpClient client = new DefaultHttpClient();
    		url = url.replace(" ", "%20");
        	HttpGet request = new HttpGet(url);	
        	HttpResponse response = client.execute(request);
        	if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
	    	{
	    		InputStream is = response.getEntity().getContent();
	            	            
	            SAXParserFactory spf = SAXParserFactory.newInstance();
	            SAXParser sp = spf.newSAXParser();				
				
	            // SAX Parser handler
	            DefaultHandler handler = new DefaultHandler() {
					private boolean id = false;
					private boolean restaurant = false;
					private boolean time = false;
					
					public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
					{						
						if (qName.equalsIgnoreCase("id")) {
							id = true;
						}
						
						if (qName.equalsIgnoreCase("restaurant")) {
							restaurant = true;
						}
						
						if (qName.equalsIgnoreCase("time")) {
							time = true;
						}
					}
					
					public void characters(char ch[], int start, int length) throws SAXException 
					{
						if (id) {
							strId = new String(ch, start, length);
							id = false;
						}
						
						if (restaurant) {
							strRestaurant = new String(ch, start, length);
							restaurant = false;
						}
						
						if (time) {
							strTime = new String(ch, start, length);
							time = false;
							
							HashMap<String, String> hm = new HashMap<String, String>();
							hm.put("Name", strId);
							hm.put("Restaurant", strRestaurant);
							hm.put("Time", strTime);
							friend_list.add(hm);
						}
							
					}
	            };
	            
	            sp.parse(is, handler);

	    	}
    	}
    	catch (Exception e) {}
    }
    
    private String encrypt(String input) {
		  DESKeySpec keySpec;
		  try {
				keySpec = new DESKeySpec(PASSPHRASE.getBytes("UTF8"));
				SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
				SecretKey key = keyFactory.generateSecret(keySpec);
				  
				// ENCODE plainTextPassword String
				byte[] cleartext = input.getBytes("UTF8");      
				  
				Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
				cipher.init(Cipher.ENCRYPT_MODE, key);
				String encrypedPwd = new String(Base64.encodeBase64(cipher.doFinal(cleartext)));		  
				  
				return encrypedPwd;
		  } catch (Exception e) {
				e.printStackTrace();
		  }
		  
		  return null;
	   }
    
    private class FriendAdapter extends ArrayAdapter<HashMap<String, String>> {
    	 
        private ArrayList<HashMap<String, String>> items;
 
        public FriendAdapter(Context context, int textViewResourceId, ArrayList<HashMap<String, String>> items) {
                 super(context, textViewResourceId, items);
                 this.items = items;
         }
        
         @Override
         public View getView(int position, View convertView, ViewGroup parent) {
                 View v = convertView;
                 if (v == null) {
                     LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                     v = vi.inflate(R.layout.friendrow, null);
                 }
                 
                 HashMap<String, String> o = items.get(position);
                 if (o != null) {
                         TextView tt = (TextView) v.findViewById(R.id.firstLine);
                         TextView bt = (TextView) v.findViewById(R.id.secondLine);
                         if (tt != null) 
                               tt.setText(o.get("Name")); 
                         
                         if(bt != null)
                               bt.setText("At: " + o.get("Restaurant") + " (" + o.get("Time") + ")");
                 }
                 return v;
         }
    }
 
	
}
